package com.caimiao.miao.library.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * SoundPool：支持多个音频文件同时播放(组合音频也是有上限的)，延时短，比较适合短促、密集的场景，是游戏开发中音效播放的福音
 */
public class VoiceSoundPlayer implements SoundPool.OnLoadCompleteListener {
    private static VoiceSoundPlayer instance;

    private SoundPool mPlayer;
    private Map<String, Integer> mMapSoundId;
    private int mStreamId;

    public static VoiceSoundPlayer getInstance() {
        if (instance == null)
            instance = new VoiceSoundPlayer();
        return instance;
    }

    private VoiceSoundPlayer() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mPlayer = new SoundPool(5, AudioManager.STREAM_MUSIC, 8);
        } else {
            AudioAttributes attr = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build();
            mPlayer = new SoundPool.Builder()
                    .setMaxStreams(5)
                    .setAudioAttributes(attr)
                    .build();
        }
        mPlayer.setOnLoadCompleteListener(this::onLoadComplete);
        mMapSoundId = new HashMap<>();
    }

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {

    }

    public void loadFromAsset(Context context, String fileName, int priority) {
        try {
            if (!mMapSoundId.containsKey(fileName)) {
                AssetFileDescriptor afd = context.getAssets().openFd(fileName);
                mMapSoundId.put(fileName, mPlayer.load(afd, priority));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void loadFromRes(Context context, int resId, int priority) {
        if (!mMapSoundId.containsKey(String.valueOf(resId))) {
            mMapSoundId.put(String.valueOf(resId), mPlayer.load(context, resId, priority));
        }
    }

    public void loadFromFile(String path, int priority) {
        if (!mMapSoundId.containsKey(path)) {
            mMapSoundId.put(path, mPlayer.load(path, priority));
        }
    }

    public void play(String key) {
        if (mMapSoundId.containsKey(key)) {
            mPlayer.stop(mStreamId);//主动停止上一个音频播放
            mStreamId = mPlayer.play(mMapSoundId.get(key), 1, 1, 1, 1, 1);
        }
    }

    public void release() {
        mPlayer.release();
    }
}
